import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { getToken,removeToken } from '@/utils/auth'
let apiUrl ='http://47.108.92.210:8182/'
//let apiUrl ='http://sdprod.szlcar.com:8182/'
const service = axios.create({
  baseURL: apiUrl,
  timeout: 15000
})
service.interceptors.request.use(
  config => {
    if(config.method=='get'){
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }else{
      config.headers['Content-Type'] = 'application/json'
    }
    if(config.url!='/login')
      config.headers['Authorization'] = getToken()
    return config
  },
  error => {
    console.log(error) 
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code == 401) {
      MessageBox.alert('由于您长时间未使用系统,登录验证已过期，请重新登录!', '温馨提示', {
        confirmButtonText: '确定',
        callback: action => {
          removeToken()
          window.location.href= window.location.origin+'/#/login'
        }
      })
      return false
    } else if(res.code==200) {
      return res
    }else{
      Message({
        message:res.msg || '网络错误',
        type: 'error',
        duration:3000
      })
      return res
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: '网络错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

export function getUrl() {
  return  apiUrl
}